package org.zpmis.configurer;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;
import org.zpmis.common.enums.LangEnum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import java.util.Objects;

/**
 * 国际化支持
 *
 * @author LENOVO
 */
@Slf4j
public class LanguageLocaleResolver implements LocaleResolver {

    public static Locale localeResolver() {
        LangEnum langEnum = LangEnum.CN;
        String lang = "";
        if (Objects.nonNull(RequestContextHolder.getRequestAttributes())) {
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
            lang = request.getHeader("Lang");
        }
        if (Objects.nonNull(lang) && StringUtils.isNotBlank(lang)) {
            langEnum = LangEnum.getByCode(lang) == null ? LangEnum.EN : LangEnum.getByCode(lang);
        }
        return new Locale(langEnum.language(), langEnum.area());
    }

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        return localeResolver();
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}
